﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Elight.Entity;
using Elight.Service.Interfaces;
using Elight.Repository.Interfaces;
using Elight.Infrastructure.Extensions;

namespace Elight.Service
{
    public partial class UserSigninService : BaseService<Sys_User_Signin>, IUserSigninService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUserSigninRepository _userSigninRepository;

        public UserSigninService(
            IUserRepository userRepository,
            IUserSigninRepository userSigninRepository)
        {
            _userRepository = userRepository;
            _userSigninRepository = userSigninRepository;
        }

        public Tuple<Sys_User, string> Validate(string userName, string password)
        {
            var userEntity = _userRepository.GetByUserName(userName);

            if (userEntity == null)
            {
                return new Tuple<Sys_User, string>(null, "系统不存在该用户，请重新确认。");
            }

            if (!userEntity.IsEnable)
            {
                return new Tuple<Sys_User, string>(null, "该用户已被禁用，请联系管理员。");
            }

            var userSinginEntity = _userSigninRepository.GetByUserId(userEntity.Id);

            string inputPassword = password.DESEncrypt(userSinginEntity.SecretKey).Md5Encrypt();

            if (inputPassword != userSinginEntity.Password)
            {
                return new Tuple<Sys_User, string>(null, "密码错误，请重新输入。");
            }
            else
            {
                return new Tuple<Sys_User, string>(userEntity, "恭喜您，通过系统认证。");
            }
        }
    }
}
